﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mortgage.DAL.Entity;
using System.Web.Security;

namespace Mortgage.Form
{
    public partial class InterestRate : System.Web.UI.Page
    {
        Mortgage.Srv.IInterestRateSrv svc = Mortgage.Srv.SrvFactory.CreateInterestRateSrv();

        #region Event handler
        protected void Page_Load(object sender, EventArgs e)
        {
            this.grid.RowDataBound += new GridViewRowEventHandler(grid_RowDataBound);
            if (!this.IsPostBack)
            {
                BindInterestTalbe(drpConfigType);
                BindGridView();
                BindAgentFilter();

                FormMode = EnmFormMode.Blank;
                HandleFormState(FormMode);
            }
        }

        void grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
                e.Row.Attributes["onmouseout"] = "this.style.cursor='default';";

                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grid, "Select$" + e.Row.RowIndex);
            }
        }

        protected void grid_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(grid.DataKeys[grid.SelectedIndex].Value.ToString());
            tInterestRate usr = svc.GetById(id);
            if (usr == null)
                Entity = new tInterestRate();
            else
                Entity = usr;

            // Update mode
            FormMode = EnmFormMode.Edit;
            HandleFormState(FormMode);
            BindView();
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            // Update mode
            Entity = new tInterestRate() { ID = 0 };
            FormMode = EnmFormMode.Insert;
            HandleFormState(FormMode);
            BindView();

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;
            BindEntity();
            // clear error Message
            DialogMess.Text = string.Empty;
            DialogMess.CssClass = "successBox";
            if (FormMode == EnmFormMode.Insert) // Insert Mode
            {

                try
                {
                    if (svc.Insert(Entity) == 0)
                    {
                        DialogMess.Text = "Cập nhật thành công!";
                        BindGridView();

                        // Translate to update mode
                        // Update mode
                        FormMode = EnmFormMode.Edit;
                        HandleFormState(FormMode);
                        BindView();
                    }
                }
                catch (Exception ex)
                {
                    DialogMess.Text = ex.Message;
                    DialogMess.CssClass = "failureBox";
                }


            }
            else
            {

                if (svc.Update(Entity) == 0)
                {

                    DialogMess.Text = "Cập nhật thành công!";
                    BindGridView();

                    // Translate to update mode
                    // Update mode
                    FormMode = EnmFormMode.Edit;
                    HandleFormState(FormMode);
                    BindView();
                }


            }

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            BindEntity();
            svc.Delete(Entity);
            BindGridView();
            FormMode = EnmFormMode.Blank;
            HandleFormState(FormMode);
        }

        protected void btnFilter_Click(object sender, EventArgs e)
        {
            HandleFilter();
        }
          
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            FormMode = EnmFormMode.Blank;
            HandleFormState(FormMode);
        }

        protected void grid_Sorting(object sender, GridViewSortEventArgs e)
        {
            
        }

        #endregion


        #region Property

        public tInterestRate Entity
        {
            get;
            set;
        }

        public EnmFormMode FormMode
        {
            get
            {
                if (ViewState["_ViewState"] == null)
                    return EnmFormMode.Blank;
                EnmFormMode result = (EnmFormMode)Enum.Parse(typeof(EnmFormMode), ViewState["_ViewState"].ToString());
                return result;

            }
            set
            {
                ViewState["_ViewState"] = value;
            }
        }

        #endregion

        #region Bind function

        protected void HandleFilter()
        {


            int cfgId = Convert.ToInt32(drpConfigType.SelectedValue);
            int? parCfgId;
            if (cfgId == -1) // Select All Agent
                parCfgId = null;
            else
                parCfgId = cfgId;



            int agentId = Convert.ToInt32(drpFilterAgent.SelectedValue);
            int? parAgentId;
            if (agentId == -1) // Select All
                parAgentId = null;
            else
                parAgentId = agentId;


            DateTime dteUse = new DateTime();
            DateTime? parDteUse = null;
            if (!string.IsNullOrEmpty(fldFilterDate.Text))
            {
                Utility.ParseDateTime(fldFilterDate.Text, out dteUse);

                parDteUse = dteUse;
            }

            grid.DataSource = svc.Find(parCfgId, parDteUse, parAgentId);
            grid.DataBind();


        }

        protected void BindAgentFilter()
        {
            Mortgage.Srv.IAgentSrv svcAgent = Mortgage.Srv.SrvFactory.CreateAgentSrv();
            drpFilterAgent.DataSource = svcAgent.GetAll();
            drpFilterAgent.DataBind();

            int selAgentId = Utility.AgentId;
            drpFilterAgent.SelectedValue = selAgentId.ToString();

        }

        protected void BindGridView()
        {
            // Perform filter
            grid.DataSource = svc.GetAllInterestInfo();
            grid.DataBind();

        }

        void BindInterestTalbe(DropDownList drpInterest)
        {

            drpInterest.DataSource = null;
            //drpConfigType.SelectedItem = null;
            drpConfigType.ClearSelection();

            drpInterest.DataSource = svc.GetConfigIntestName();
            drpInterest.DataBind();

        }

        protected void HandleFormState(EnmFormMode state)
        {
            switch (state)
            {
                case EnmFormMode.Blank:
                    btnCancel.Enabled = false;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = true;
                    btnSave.Enabled = false;


                    BlankControl();
                    EnableControl(false);
                    Entity = new tInterestRate();

                    break;
                case EnmFormMode.Edit:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;

                    EnableControl(true);
                    fldStartDate.Enabled = false; // Edit can not delete

                    break;
                case EnmFormMode.Insert:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = false;
                    btnSave.Enabled = true;

                    EnableControl(true);

                    break;
            }

            BindView();
        }

        protected void EnableControl(bool enable)
        {

            fldName.Enabled = enable;
            fldInterestRate.Enabled = enable;
            fldNumOfDayExpire.Enabled = enable;
            fldStartDate.Enabled = enable;
            fldDescription.Enabled = enable;
        }

        protected void BindView()
        {
            if (Entity.ID <= 0)
            {
                BlankControl();
                return;
            }

            BindInterestTalbe(fldName);

            fldInterestRate.Text = Entity.InterestRate.ToString();
            fldNumOfDayExpire.Text = Entity.NumOfDayExpire.ToString();
            fldStartDate.Text = Utility.FormatDateTime(Entity.BeginDate);
            if (Entity.EndDate.HasValue)
                fldEndDate.Text = Utility.FormatDateTime(Entity.EndDate.Value);
            else
                fldEndDate.Text = string.Empty;
            fldID.Value = Entity.ID.ToString();
            fldDescription.Text = Entity.Description;
        }

        protected void BindEntity()
        {
            tInterestRate entity = new tInterestRate();
            if (Entity != null)
                entity.ID = Entity.ID;

            int id = 0;
            int.TryParse(fldID.Value, out id);
            entity.ID = id;
            entity.CodeId = Convert.ToInt32(fldName.SelectedItem.Value);
            entity.InterestRate = Convert.ToDecimal(fldInterestRate.Text.Trim());
            entity.NumOfDayExpire = Convert.ToInt32(fldNumOfDayExpire.Text.Trim());
            entity.Description = fldDescription.Text;
            DateTime dteBeginDate = new DateTime();
            if (Utility.ParseDateTime(fldStartDate.Text, out dteBeginDate) == 0)
                entity.BeginDate = dteBeginDate;
            else
            {
                // Raise error
            }



            Entity = entity;
            BindProperty();
        }

        protected void BlankControl()
        {
            fldName.ClearSelection();
            BindInterestTalbe(fldName);

            fldDescription.Text = string.Empty;
            fldNumOfDayExpire.Text = string.Empty;
            fldInterestRate.Text = string.Empty;

            fldEndDate.Text = string.Empty;
            fldStartDate.Text = string.Empty;

            DialogMess.CssClass = string.Empty;
            DialogMess.Text = string.Empty;

        }

        protected void BindProperty()
        {
            MembershipUser membershipUser = System.Web.Security.Membership.GetUser();

            if (membershipUser != null)
            {
                Entity.CreatedBy = membershipUser.UserName;
                Entity.ModifiedBy = membershipUser.UserName;
                Entity.CreatedDate = DateTime.Now;
                Entity.ModifiedDate = DateTime.Now;

                Entity.Age_ID = Utility.AgentId;

            }

        }
        #endregion

       
    }
}